import 'package:flutter/material.dart';
import 'package:practice_flutter/utils/eventbus.dart';
import 'package:practice_flutter/utils/http.dart';
import 'package:practice_flutter/utils/logger.dart';
import 'package:practice_flutter/utils/toast.dart';
import 'package:practice_flutter/utils/token.dart';

// ignore: must_be_immutable
class MainPage extends StatefulWidget {
  MainPage({super.key, required this.currentIndex});
  int currentIndex;
  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  Map userInfo = {'avatar': '', 'nickname': null, 'id': null};

  getProfile() async {
    var res = await http.get('/userInfo');
    if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
    setState(() {
      userInfo = res['data'];
      logger.i(userInfo);
    });
  }

  @override
  void didUpdateWidget(covariant MainPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      getProfile();
    }
  }

  @override
  void initState() {
    eventBus.on<RefreshMine>().listen((event) {
      getProfile();
    });
    eventBus.on<BackMine>().listen((event) {
      // ToastUtil.showSuccess('修改成功');
      getProfile();
    });
    super.initState();
  }

  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      ),
      body: SafeArea(
          child: Container(
        padding: const EdgeInsets.all(10),
        color: const Color.fromARGB(200, 85, 145, 175),
        child: Column(
          children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(50),
                  child: userInfo['avatar'] != ''
                      ? Image.network(
                          userInfo['avatar'],
                          width: 50,
                          height: 50,
                        )
                      : Image.asset(
                          'assets/images/avatar_1.jpg',
                          width: 50,
                          height: 50,
                        ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Text(
                  userInfo['nickName'] ?? '用户名',
                  style: const TextStyle(color: Colors.white),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, '/profile',
                        arguments: userInfo);
                  },
                  child: const Row(
                    children: [
                      Text(
                        '去完善信息',
                        style: TextStyle(color: Colors.white),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.white,
                        size: 13,
                      )
                    ],
                  ),
                )
              ],
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(10)),
              padding: const EdgeInsets.only(
                  top: 20, bottom: 20, left: 15, right: 15),
              margin: const EdgeInsets.only(top: 20),
              child: Column(
                  children: menuList.map((item) {
                return GestureDetector(
                    onTap: () {},
                    child: SizedBox(
                      height: 50,
                      child: Row(
                        children: [
                          Image.asset(
                            item['icon'],
                            width: 25,
                            height: 25,
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          Text(item['title']),
                          const Spacer(),
                          const Icon(
                            Icons.arrow_forward_ios,
                            size: 12,
                            color: Colors.grey,
                          )
                        ],
                      ),
                    ));
              }).toList()),
            ),
            ElevatedButton(
                onPressed: () async {
                  // TokenManager().saveToken('2192189298198219821');
                  final res = await http.get('/house');
                  logger.i(res);
                },
                child: const Text('请求测试401')),
            const SizedBox(height: 20),
            SizedBox(
              height: 40,
              width: 200,
              child: ElevatedButton(
                  style: ButtonStyle(
                      shape: WidgetStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(0)))),
                  onPressed: () {
                    TokenManager().removeToken();
                  },
                  child: const Text('删除token')),
            )
          ],
        ),
      )),
    );
  }
}
